<?php

namespace App\Http\Controllers\Admin;


use App\Models\BlackAccount;
use App\Models\Config;
use App\Models\Order;
use App\Services\Service\Helper;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Numa\Aodao\NumaException;
use Numa\Aodao\Yhcc;

class AccountController extends BaseController
{
    //
    public function __construct()
    {
    }

    /**
     * 账号黑名单
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function blacklist(Request $request)
    {
        //
        $inputs = Helper::getInputs($request, ['opt_type' => '', 'keywords' => '', 'page' => 1, 'limit' => 10]);
        $page = intval($inputs['page']);
        $limit = intval($inputs['limit']);
        $start = ($page - 1) * $limit;

        $where = [];
        $where['where'][] = [
            'is_delete' => 0
        ];
        if ($inputs['opt_type'] != '' && $inputs['keywords'] != '') {
            if (in_array($inputs['opt_type'], ['user_id'])) {
                $where['where'][] = [$inputs['opt_type'] => $inputs['keywords']];
            } elseif ($inputs['opt_type'] == 'username') {
                $where['whereHas'][] = ['user', function ($query) use ($inputs) {
                    $query->where('nickname', 'like', '%' . $inputs['keywords'] . '%');
                }];
            } else {
                $where['where'][] = [$inputs['opt_type'], 'like', '%' . $inputs['keywords'] . '%'];
            }
        }
        $result = BlackAccount::queryAll($where, [], [$start, $limit]);
        $result['conditions'] = $inputs;
        return $this->display('account.blacklist', $result);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Request $request)
    {
        return $this->display('account.add');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
        if ($request->ajax()) {
            $account_no = $request->input('account_no', '');
            if ($account_no == '') {
                return $this->error('请填写旺旺号');
            }
            if (BlackAccount::isExist($account_no)) {
                return $this->error('已经存在账号:' . $account_no . '的黑名单记录');
            }
            $comm = $request->input('comm', '');
            if ($comm == '') {
                return $this->error('请填写拉黑原因');
            }

            $account = new BlackAccount();
            $account->account_no = $account_no;
            $account->comm = $comm;
            $account->user_id = Auth::id();
            if (false !== $account->save()) {
                return $this->success('新增成功', ['redirect' => url('account/blacklist')]);
            } else {
                return $this->error('新增失败');
            }
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request, $id)
    {
        if ($request->ajax()) {
            $account = BlackAccount::find($id);
            if (is_null($account)) {
                return $this->error('查找账号信息失败');
            }
            $account->is_delete = 1;
            if (false !== $account->save()) {
                return $this->success('删除成功');
            } else {
                return $this->error('删除失败');
            }
        }
    }

    /**
     * 账号校验页面/调用接口获取账号信息
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\JsonResponse|\Illuminate\View\View
     */
    public function check(Request $request)
    {
        if ($request->ajax() && $request->isMethod('post')) {
            //获取账号信息
            $account_no = $request->input('account_no', '');
            if ($account_no == '') {
                return $this->error('账号不能为空');
            }
            try {
                //调用优号查查接口获取
                $result = Yhcc::info($account_no);
                $info = ['hasInfo' => 0];
                $images = [];
                if ($result['code'] == 1) {
                    $data = $result['data'];
                    $images = isset($data['datas']) ? $data['datas'] : [];
                    unset($data['datas']);
                    $info = array_merge($data, ['hasInfo' => 1]);
                } else {
                    Log::notice("查询账号:" . $account_no . "[" . $result['message'] . "]");
                }
                //获取该账号在本地的补单记录
                $content = [];
                $wheres = [];
                $wheres['where'][] = ['account_no', '=', $account_no];
                $wheres['where'][] = ['status', '!=', -1];
                $result = Order::queryAll($wheres);
                $count = $result['counts'];
                $orders = $result['datas'];
                $content['nodata'] = $count ? 0 : 1;
                //
                $doing = 0;
                $datas = [];
                $lasttime = "";
                $nums = 0;
                $money = 0;
                $commission = 0;
                foreach ($orders as $order) {
                    $status = $order->status;
                    if ($status != 4) {
                        $doing++;
                    } else {
                        if ($lasttime == '') {
                            $lasttime = $order->order_time;
                        }
                        $nums++;
                        $money += $order->price;
                        $commission += $order->commission;
                        $datas = $this->_getDetail($datas, $order);
                    }
                }

                $content['doing'] = $doing;
                $content['lasttime'] = $lasttime;
                $content['datas'] = $datas;
                $content['nums'] = $nums;
                $content['money'] = number_format($money, 2);
                $content['commission'] = number_format($commission, 2);
                return $this->success('success', compact('info', 'images', 'content'));
            } catch (NumaException $exception) {
                return $this->error($exception->getMessage());
            }
        }
        return $this->display('account.check');
    }

    /**
     * 根据订单获取详情
     *
     * @param $order
     * @return array
     */
    private function _getDetail($datas, $order)
    {
        $ordertime = strtotime($order->order_time);
        $diff = floor((time() - $ordertime) / 86400);
        $datas[$order->shop_id]['shop_title'] = !is_null($order->shop) ? $order->shop->title : '';
        if (!isset($datas[$order->shop_id]['num_1'])) {
            $datas[$order->shop_id]['num_1'] = 0;
            $datas[$order->shop_id]['money_1'] = 0;
            $datas[$order->shop_id]['commission_1'] = 0;
        }
        if (!isset($datas[$order->shop_id]['num_2'])) {
            $datas[$order->shop_id]['num_2'] = 0;
            $datas[$order->shop_id]['money_2'] = 0;
            $datas[$order->shop_id]['commission_2'] = 0;
        }
        if (!isset($datas[$order->shop_id]['num_3'])) {
            $datas[$order->shop_id]['num_3'] = 0;
            $datas[$order->shop_id]['money_3'] = 0;
            $datas[$order->shop_id]['commission_3'] = 0;
        }
        if (!isset($datas[$order->shop_id]['num_4'])) {
            $datas[$order->shop_id]['num_4'] = 0;
            $datas[$order->shop_id]['money_4'] = 0;
            $datas[$order->shop_id]['commission_4'] = 0;
        }
        if (!isset($datas[$order->shop_id]['num_5'])) {
            $datas[$order->shop_id]['num_5'] = 0;
            $datas[$order->shop_id]['money_5'] = 0;
            $datas[$order->shop_id]['commission_5'] = 0;
        }
        if ($diff >= 180) {//6个月前
            $datas[$order->shop_id]['num_5'] += 1;
            $datas[$order->shop_id]['money_5'] += $order->price;
            $datas[$order->shop_id]['commission_5'] += $order->commission;
        } else {
            if ($diff < 7) {
                $datas[$order->shop_id]['num_1'] += 1;
                $datas[$order->shop_id]['num_2'] += 1;
                $datas[$order->shop_id]['num_3'] += 1;
                $datas[$order->shop_id]['num_4'] += 1;

                $datas[$order->shop_id]['money_1'] += $order->price;
                $datas[$order->shop_id]['money_2'] += $order->price;
                $datas[$order->shop_id]['money_3'] += $order->price;
                $datas[$order->shop_id]['money_4'] += $order->price;

                $datas[$order->shop_id]['commission_1'] += $order->commission;
                $datas[$order->shop_id]['commission_2'] += $order->commission;
                $datas[$order->shop_id]['commission_3'] += $order->commission;
                $datas[$order->shop_id]['commission_4'] += $order->commission;
            } elseif ($diff < 30) { //30天内
                $datas[$order->shop_id]['num_2'] += 1;
                $datas[$order->shop_id]['num_3'] += 1;
                $datas[$order->shop_id]['num_4'] += 1;

                $datas[$order->shop_id]['money_2'] += $order->price;
                $datas[$order->shop_id]['money_3'] += $order->price;
                $datas[$order->shop_id]['money_4'] += $order->price;

                $datas[$order->shop_id]['commission_2'] += $order->commission;
                $datas[$order->shop_id]['commission_3'] += $order->commission;
                $datas[$order->shop_id]['commission_4'] += $order->commission;
            } elseif ($diff < 90) { //90天内
                $datas[$order->shop_id]['num_3'] += 1;
                $datas[$order->shop_id]['num_4'] += 1;

                $datas[$order->shop_id]['money_3'] += $order->price;
                $datas[$order->shop_id]['money_4'] += $order->price;

                $datas[$order->shop_id]['commission_3'] += $order->commission;
                $datas[$order->shop_id]['commission_4'] += $order->commission;
            } else {//半年内
                $datas[$order->shop_id]['num_4'] += 1;
                $datas[$order->shop_id]['money_4'] += $order->price;
                $datas[$order->shop_id]['commission_4'] += $order->commission;
            }
        }
        return $datas;
    }

    /**
     * 查看最新10条评论记录
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\JsonResponse|\Illuminate\View\View
     */
    public function rate(Request $request)
    {
        //获取账号信息
        $account_no = $request->input('account_no', '');
        if ($account_no == '') {
            return $this->error('账号不能为空');
        }
        $datas = [];
        try {
            //调用优号查查接口获取
            $result = Yhcc::rate($account_no);
            if ($result['code'] == 1) {
                $datas = $result['data']['datas'];
            } else {
                Log::notice("查询账号:" . $account_no . "[" . $result['message'] . "]");
            }
        } catch (NumaException $exception) {
            Log::notice("查询账号:" . $account_no . "的评价记录失败" . $exception->getMessage());
        }
        $this->assign('datas', $datas);
        return $this->display('account.rate');
    }
}
